package com.terren.webdig.setting.controller;

import java.awt.image.RenderedImage;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.terren.webdig.basic.BasicControllerSupport;
import com.terren.webdig.common.annotation.AuthLoginAnnotation;
import com.terren.webdig.common.config.ConfigInfo;
import com.terren.webdig.common.entity.LoginSessionContext;
import com.terren.webdig.common.util.CodeUtil;
import com.terren.webdig.common.util.CommonUtil;
import com.terren.webdig.common.util.StringUtil;
import com.terren.webdig.setting.entity.Function;
import com.terren.webdig.setting.entity.LoginUser;
import com.terren.webdig.setting.entity.SysLog;
import com.terren.webdig.setting.service.IFunctionService;
import com.terren.webdig.setting.service.IUserLoginService;

/**
 * 登陆controller
 * https://blog.csdn.net/figo0423/article/details/79759151 springmvc页面跳转方式
 * @author Administrator
 *
 */
@Controller
@RequestMapping(value = "/user")
public class UserLoginController extends BasicControllerSupport {
	
	@Resource(name = "functionService")
	protected IFunctionService functionService;
	@Resource(name = "userLoginService")
	protected IUserLoginService userLoginService;
	/**
	 * 初始登录跳转
	 * @return
	 */
	@AuthLoginAnnotation
	@RequestMapping(value = "/userLogin", method = RequestMethod.GET)
	public String userLogin() {
		return "common/login";
	}
	/**
	 * 跳转到main.jsp
	 * @return
	 */
	/*@RequestMapping(value = "/main", method = RequestMethod.GET)
	public String main() {
		return ConfigInfo.mainPage;
	}*/
	/**
	 * 登录验证
	 * @param request
	 * @param session
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@AuthLoginAnnotation
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(HttpServletRequest request, HttpSession session, HttpServletResponse response) throws Exception {
		LoginUser param = (LoginUser) CommonUtil.getParameterObject(LoginUser.class, request);
		param.setUserName(StringUtil.getFromBase64(param.getUserName()));
		param.setPassword(StringUtil.getFromBase64(param.getPassword()));
		log.info("用户名："+param.getUserName()+"，密码："+param.getPassword());
		String ip = CommonUtil.getLoginIp(request);
		Map<String, HttpSession> sessionMap = LoginSessionContext.getInstance().getSessionList();
		String result = ERROR;
		try {
			// 验证用户名是否存在
			boolean flag = userLoginService.validateUserName(param);
			if (!flag) {
				result = "redirect:/user/userLogin?type=1";
				return result;
			}
			LoginUser loginUser = userLoginService.userLogin(param);// 验证密码
			SysLog sysLog = new SysLog();
			if (null != loginUser && loginUser.getStatus() == 1) {// 验证成功
				log.info("#### user login : " + ip);
				List<Function> functionList = functionService.getUserFunction(loginUser);// 获取用户功能列表
				functionService.initUserFunction(loginUser, functionList);// 初始化功能列表
				session.setAttribute(ConfigInfo.SESSION_USER, loginUser);
				//setFunctionToSession(session);
				/**
				 * 登陆成功，将登入的用户信息录入数据库
				 */
				sysLog.setLogType("1");
				/**
				 * 将登陆成功的用户信息存入 sessionMap
				 */
				sessionMap.put(session.getId(), session);
				result = "redirect:/user/fun";
			} else if (null != loginUser && loginUser.getStatus() == 0) {// 账号停用
				sysLog.setLogType("2");
				result = "redirect:/user/userLogin?type=2";
			} else {// 验证失败
				sysLog.setLogType("3");
				result = "redirect:/user/userLogin?type=3";
			}
			if (loginUser == null) {
				List<LoginUser> list = userLoginService.getUserId(param);
				if (list.size() != 0) {
					sysLog.setUserId(list.get(0).getUserId());
				}
			} else {
				sysLog.setUserId(loginUser.getUserId());
			}
			sysLog.setUserName(param.getUserName());
			sysLog.setSessionId(session.getId());//
			sysLog.setIp(ip);
			log.info("#### user [" + param.getUserName() + "] login : " + ip);
			return result;
		} catch (Exception e) {
			session.removeAttribute(ConfigInfo.SESSION_USER);
			log.error("用户登录异常错误", e);
			return "redirect:/user/userLogin?type=4";
		}
	}

	/**
	 * Login 跳转
	 * 
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	/*@RequestMapping(value = "/loginTo", method = RequestMethod.POST)
	public String loginTo(HttpServletRequest request, HttpSession session, HttpServletResponse response)
			throws UnsupportedEncodingException {
		LoginUser param = new LoginUser();
		String userName = request.getParameter("userName"); // 应急中心那边字段与这边不一样
		String ssoPassword = request.getParameter("password");
		// nec用户功能编号
		String functionId = request.getParameter("functionId");
		session.setAttribute("functionId", functionId);
		// 内刊选题综合热点参数
		String keyword = request.getParameter("keyword");
		String startDay = request.getParameter("startDay");
		String endDay = request.getParameter("endDay");
		String field = request.getParameter("field");
		session.setAttribute("keyword", keyword);
		session.setAttribute("startDay", startDay);
		session.setAttribute("endDay", endDay);
		session.setAttribute("field", field);

		userName = URLDecoder.decode(userName, "UTF-8");
		String ip = CommonUtil.getLoginIp(request);
		param.setUserName(userName);
		Map<String, HttpSession> sessionMap = LoginSessionContext.getInstance().getSessionList();
		String result = ERROR;
		try {
			// 验证用户名是否存在
			LoginUser user = userLoginService.getUserByName(param);
			if (user == null) {
				return result;
			}
			SysLog sysLog = new SysLog();
			String userPassword = userName + user.getPassword();
			userPassword = DigestUtils.sha1Hex(userPassword);
			if (userPassword.equals(ssoPassword) && user.getStatus() == 1) {// 验证成功
				log.info("#### user login : " + ip);
				List<Function> functionList = functionService.getUserFunction(user);// 获取用户功能列表
				functionService.initUserFunction(user, functionList);// 初始化功能列表
				session.setAttribute(ConfigInfo.SESSION_USER, user);
				setFunctionToSession(session);
				*//**
				 * 登陆成功，将登入的用户信息录入数据库
				 *//*
				sysLog.setLogType("1");
				*//**
				 * 将登陆成功的用户信息存入 sessionMap
				 *//*
				sessionMap.put(session.getId(), session);
				result = SUCCESS;
			} else if (null != user && user.getStatus() == 0) {// 账号停用
				sysLog.setLogType("2");
				result = NONE;
			} else {// 验证失败
				sysLog.setLogType("3");
				result = ERROR;
			}
			sysLog.setUserId(user.getUserId());
			sysLog.setUserName(param.getUserName());
			sysLog.setSessionId(session.getId());//
			sysLog.setIp(ip);
			log.info("#### user [" + param.getUserName() + "] login : " + ip);
			sysLogService.loginLog(sysLog);
			return result;
		} catch (Exception e) {
			session.removeAttribute(ConfigInfo.SESSION_USER);
			log.error("用户登录异常错误", e);
			return "server_error";
		}

	}*/

	/**
	 * 注销
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/logout",method=RequestMethod.GET)	
	public String logout(HttpServletRequest request ,HttpSession session , HttpServletResponse response) throws Exception {
		session.removeAttribute(ConfigInfo.SESSION_USER);
		session.invalidate();
		return "redirect:/user/userLogin";
	}
	/**
	 * 拦截的功能跳转
	 * @return
	 */
	@RequestMapping(value = "/fun",method=RequestMethod.GET)	
	public void fun(HttpServletRequest request ,HttpSession session , HttpServletResponse response){
		this.forward(ConfigInfo.ActionValue, request, session, response);
	}
	/**
	 * 非拦截的功能跳转
	 * 
	 * @return
	 */
	@RequestMapping(value = "/opfun",method=RequestMethod.GET)	
	public void opfun(HttpServletRequest request ,HttpSession session , HttpServletResponse response) {
		this.forward(ConfigInfo.opActionValue, request, session, response);
	}

	/**
	 * 非拦截的功能跳转
	 * 
	 * @return
	 */
	@RequestMapping(value = "/defun",method=RequestMethod.GET)	
	public void defun(HttpServletRequest request ,HttpSession session , HttpServletResponse response) {
		this.forward(ConfigInfo.deActionValue, request, session, response);
	}
	/**
	 * 获取验证码
	 * 
	 * @return
	 * @throws IOException 
	 */
	@AuthLoginAnnotation
	@RequestMapping(value = "/getCode",method=RequestMethod.GET)	
	public void getCode(HttpServletRequest rest ,HttpSession session , HttpServletResponse resp) throws IOException {
		// 调用工具类生成的验证码和验证码图片
        Map<String, Object> codeMap = CodeUtil.generateCodeAndPic();
        session.setAttribute("code", codeMap.get("code").toString());
        // 禁止图像缓存。
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", -1);
        resp.setContentType("image/jpeg");
        // 将图像输出到Servlet输出流中。
        ServletOutputStream sos = resp.getOutputStream();
        ImageIO.write((RenderedImage) codeMap.get("codePic"), "jpeg", sos);
        sos.close();
	}
	// 把所有的功能名称存到session里，添加系统日志的时候会用到
	/*private void setFunctionToSession(HttpSession session) throws Exception {
		Function function = new Function();
		List<Function> allFunctionList = functionService.getAllFunction(function);
		Map<String, List<String>> map = new HashMap<String, List<String>>();
		String newFunctionK = "";
		if (allFunctionList != null) {
			for (int i = 0; i < allFunctionList.size(); i++) {
				newFunctionK = allFunctionList.get(i).getK().toUpperCase();
				List<String> valueList = new ArrayList<String>();
				valueList.add(allFunctionList.get(i).getFunctionParentName());
				valueList.add(allFunctionList.get(i).getChildName());
				map.put(newFunctionK, valueList);
			}
		}
		session.setAttribute(ConfigInfo.SESSION_FUNCTION, map);
	}*/

	/**
	 * 跳转处理
	 * @param option
	 * @param request
	 * @param session
	 * @param response
	 * @throws Exception
	 */
	private void forward(String option,HttpServletRequest request,HttpSession session,HttpServletResponse response) {
		String k = request.getParameter("k");/** 功能跳转值 **/
		log.debug(option);
		try {
			LoginUser sessionUser = (LoginUser) session.getAttribute(ConfigInfo.SESSION_USER);
			Function userFunction = functionService.getResponseFunction(sessionUser, option, k, request);
	
			if (userFunction == null) {
				request.setAttribute("pageUrl", ConfigInfo.NO_PERMISSION_PAGE);
				request.setAttribute("pageTitle", ConfigInfo.NO_PERMISSION_PAGE_TITLE);
			} else {
				request.setAttribute("pageUrl", userFunction.getFunctionUrl());
				request.setAttribute("pageTitle", userFunction.getFunctionName());
				request.setAttribute("pageIcon", userFunction.getIcon());
			}
			request.getRequestDispatcher(ConfigInfo.mainPage).forward(request, response);
		} catch (Exception e) {
			log.error(option + "页面跳转错误", e);
		} 
	}

}
